package com.spark.check

import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.check.model.ToChkApproveModel
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.toast
import com.spark.common.ext.wrapIO
import com.spark.common.model.ResultModel
import com.spark.common.net.Http
import kotlinx.android.synthetic.main.frag_be_on_duty_detail.*
import kotlinx.android.synthetic.main.frag_result_summary.*
import kotlinx.android.synthetic.main.frag_to_chk_approve.*

/**
 * ready to check and approve
 */
class ToChkApproveFragment : BaseFragment() {
    private var tabStr = mutableListOf("结果汇总", "分值详情", "人员详情")

    companion object {
        fun newInstance(): ToChkApproveFragment {
            return ToChkApproveFragment()
        }
    }

    private var toChkApproveModel: ToChkApproveModel? = null

    override fun contentResId(): Int {
        return R.layout.frag_to_chk_approve
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        iv_back.setOnClickListener { activity?.finish() }

        fetchToCheckApproveTasks()
        // todo 此处缺少获取 结果汇总、分值详情、人员详情的具体界面信息接口
        activity?.apply {
            val chkApproveAdapter = ChkApproveAdapter(supportFragmentManager, tabStr)
            tabStr.forEach {
                tabs.addTab(tabs.newTab().setText(it))
            }
            pager.adapter = chkApproveAdapter
            tabs.setupWithViewPager(pager)
        }
    }

    /**
     * fetch the task of ready to chk & appove
     */
    private fun fetchToCheckApproveTasks() {
        val params = mutableMapOf(
                Pair(Const.qr_taskid, "$id")
        )
        activity?.apply {
            Http.request()
                    .rxPost("${Const.base_url}${Const.act_task_detail}", params)
                    .wrapIO()
                    .subscribe(
                            {
                                Gson().fromJson(it, ToChkApproveModel::class.java)?.apply {
                                    if (code == "200") {
                                        this@ToChkApproveFragment.toChkApproveModel = this
                                    } else {
                                        toast(msg)
                                    }
                                }
                            },
                            {
                                it.printStackTrace()
                                hideLoader()
                            },
                            {
                                hideLoader()
                            },
                            {
                                dispose = it
                                loading()
                            }
                    )
        }
    }

    /**
     * submit
     */
    private fun submit(mark: String = "") {
        val params = mutableMapOf(
                Pair(Const.qr_taskid, "$id"),
                Pair(Const.qr_remark, mark)
        )
        activity?.apply {
            Http.request()
                    .rxPost("${Const.base_url}${Const.act_chk_leader_chk_approve}", params)
                    .wrapIO()
                    .subscribe(
                            {
                                Gson().fromJson(it, ResultModel::class.java)?.apply {
                                    if (code == "200") {
                                        toast("提交成功")
                                        pop()
                                    } else {
                                        toast(msg)
                                    }
                                }
                            },
                            {
                                it.printStackTrace()
                                hideLoader()
                            },
                            {
                                hideLoader()
                            },
                            {
                                dispose = it
                                loading("提交中...")
                            }
                    )
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            1 -> when (resultCode) {
                1 -> if (data != null) {
                    val info = data.getStringExtra("info")
                    submit(info)
                }
            }
        }
    }
}

class ChkApproveAdapter(fm: FragmentManager, var tabs: MutableList<String>) : FragmentStatePagerAdapter(fm) {
    override fun getCount(): Int {
        return tabs.size
    }

    override fun getItem(position: Int): Fragment {
        return when (position) {
            0 -> ResultSummaryFragment.newInstance()
            1 -> BeonDutyDetailFragment.newInstance()
            else -> CrewDetailFragment.newInstance()
        }
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return tabs[position]
    }

}

/**
 * the sumamry of value
 */
class ResultSummaryFragment : BaseFragment() {
    companion object {
        fun newInstance(): ResultSummaryFragment {
            val fragment = ResultSummaryFragment()
            val args = Bundle()

            fragment.arguments = args
            return fragment
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_result_summary
    }

    override fun onSupportVisible() {
        super.onSupportVisible()
        dv_score.setValue(75)
    }
}

/**
 * be on duty
 */
class BeonDutyDetailFragment : BaseFragment() {
    companion object {
        fun newInstance(): BeonDutyDetailFragment {
            val fragment = BeonDutyDetailFragment()
            val args = Bundle()

            fragment.arguments = args
            return fragment
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_be_on_duty_detail
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val beonDutyAdapter = BeonDutyAdapter(R.layout.item_be_on_duty, BeonDutyAdapter.sum)
        recy_be_on_duty.adapter = beonDutyAdapter
        recy_be_on_duty.layoutManager = LinearLayoutManager(context)
        beonDutyAdapter.setOnItemClickListener { adapter, view, position ->

        }

        beonDutyAdapter.addData(mutableListOf(
                ToChkApproveModel.Data.Category(categoryname = "安全风险分级管控(7项)", score = 12),
                ToChkApproveModel.Data.Category(categoryname = "事故隐患排查(8项)", score = 12),
                ToChkApproveModel.Data.Category(categoryname = "通风(8项)", score = 13),
                ToChkApproveModel.Data.Category(categoryname = "地址灾害防治与测量(8项)", score = 12),
                ToChkApproveModel.Data.Category(categoryname = "安全培训和应急管理(8项)", score = 14),
                ToChkApproveModel.Data.Category(categoryname = "调度与地面设备(4项)", score = 12),
                ToChkApproveModel.Data.Category(categoryname = "职业卫生(3项)", score = 15),
                ToChkApproveModel.Data.Category(categoryname = "露天煤矿(2项)", score = 12)
        ))
    }

}

/**
 * the detail of crew
 */
class CrewDetailFragment : BaseFragment() {
    companion object {
        fun newInstance(): CrewDetailFragment {
            val fragment = CrewDetailFragment()
            val args = Bundle()

            fragment.arguments = args
            return fragment
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_be_on_duty_detail
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val beonDutyAdapter = BeonDutyAdapter(R.layout.item_be_on_duty, BeonDutyAdapter.sum)
        recy_be_on_duty.adapter = beonDutyAdapter
        recy_be_on_duty.layoutManager = LinearLayoutManager(context)
        beonDutyAdapter.setOnItemClickListener { adapter, view, position ->

        }

        beonDutyAdapter.addData(mutableListOf(
                ToChkApproveModel.Data.Category(categoryname = "检查领导", score = 1),
                ToChkApproveModel.Data.Category(categoryname = "主要责任人", score = 2),
                ToChkApproveModel.Data.Category(categoryname = "配合人", score = 3),
                ToChkApproveModel.Data.Category(categoryname = "特邀人员", score = 2)
        ))
    }

}


class BeonDutyAdapter(layoutRes: Int, var hint: Int) : BaseQuickAdapter<ToChkApproveModel.Data.Category, BaseViewHolder>(layoutRes) {
    companion object {
        const val score = 0
        const val sum = 1
    }

    override fun convert(helper: BaseViewHolder?, item: ToChkApproveModel.Data.Category?) {
        if (item == null) return
        helper?.apply {
            setText(R.id.tv_name, item.categoryname)
            setText(R.id.tv_score, "${item.score}")
            val h = if (hint == 0) "分" else "名"
            setText(R.id.tv_score_hint, h)
        }
    }

}
